#求S盒与逆S盒

import GFarith
import exsystem

gene = '100011011'

#S盒生成时的字节变换,产生16进制表
def exinS(s):
    c = [1,1,0,0,0,1,1,0]
    s = [int(i) for i in s]
    s.reverse()
    a = []
    for i in range(8):
        a.append((s[i] + s[(i+4)%8] + s[(i+5)%8] + s[(i+6)%8] + s[(i+7)%8] + c[i])%2)
    for i in range(8):
        if a[i] == 0:
            a[i] = '0'
        else:
            a[i] = '1'
    a.reverse()
    return exsystem.tohex(''.join(a))

#获得S盒
def getS():
    S = {}
    for i in range(16):
        ele = [exinS(GFarith.decinverse(gene,i*16+j)) for j in range(16)]
        S[i] = ele
    return S

#获得逆S盒
def getIS():
    IS = {}
    for i in range(16):
        ele = [GFarith.hexinverse(gene, exinIS(i*16 + j)) for j in range(16)]
        IS[i] = ele
    return IS




#逆运算时的位运算
def exinIS(s):
    c = '00000101'
    a = []
    s = exsystem.detoBi(s)
    k = {}
    for i in range(8):
        k[7-i] = int(s[i])
    for i in range(8):
        j = 7 - i
        a.append(str((k[(j+2)%8] + k[(j+5)%8] + k[(j+7)%8] + int(c[i]))%2))
    a = exsystem.tohex(''.join(a))
    return a




